﻿using CMS.DataAccess;
using CMS.Model;
using Newtonsoft.Json;
using System.Collections;

namespace CMS.Utils
{
    public class MyRefJsonConveter : JsonConverter
    {
        //static Hashtable hashtable = Hashtable.Synchronized(new Hashtable());
        MyForeignAttribute foreignAttribute;
        public MyRefJsonConveter(MyForeignAttribute foreignAttribute)
        {
            this.foreignAttribute = foreignAttribute;
            refType = foreignAttribute.RefType;
        }

        Type refType;
        public override bool CanRead => false;
        public override bool CanConvert(Type objectType)
        {
            return foreignAttribute != null && foreignAttribute.LabelProp != null;
        }

        public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
        {
            if (value == null || String.IsNullOrWhiteSpace(value?.ToString()))
            {
                serializer.Serialize(writer, value);
            }
            else
            {
                string key = $"{foreignAttribute.RefType.ToString()}.{value.ToString()}.{foreignAttribute.LabelProp}";
               /* if (hashtable.ContainsKey(key))
                {
                    serializer.Serialize(writer, hashtable[key]);
                    return;
                }*/
                var dbFuzzyQuery = new DbFuzzyQuery(ServiceLoader.GetService<DbInstance>(), foreignAttribute.RefType);
                Object result = null;
                Object obj;
                if (foreignAttribute.LabelProp != null)
                    result = dbFuzzyQuery.GetField(foreignAttribute.LabelProp, value!.ToString()!);
                if (result == null)
                {
                    serializer.Serialize(writer, value);
                }
                else
                {
                    obj = new { _k = value.ToString(), _v = result };// _ new { key = value, label = result };
                    //hashtable[key] = obj;
                    serializer.Serialize(writer, obj);
                }
            }
        }
    }
}
